import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
import {InformationMassageCount,InformationSharePictures,InformationUserCodeLogin,InformationPositioningCity,InformationUserInfo} from '@/common/http/api.js'
const store = new Vuex.Store({
    state: {
        // ossurl: 'https://golfren-1322973459.cos.ap-beijing.myqcloud.com/wx-mini'
		ossurl: 'https://cos.dingquan.vip/wx-mini',
		oss_url: 'https://cos.dingquan.vip',
		mapKey: 'IGEBZ-LRMCC-7UB26-ACSTE-BKHMH-KXFUD',
		latitude: '',
		longitude: '',
		city: '',
		cjj:'', //裁剪背景
		videoMask:'',
		//裁剪 名片
		cropperUrl: '',
		//裁剪 分享
		shareCropperUrl: '',
		//自带参数过去
		shareQuery: '',
		//发布截图
		publishUrl: '',
		//分享
		share:{},
		userInfo:{},
		messageCount: 0,
		isRefresh: true,
		isCircleRefresh: true,
		cardInfo: {},
		systemInfo:{}, //系统信息
		
		//跳转配置
		config: [
			//名片
			{
				value: 1,
				path: '/pages/loading/loading',
				jumpName: 'reLaunch'
			},
			//收藏
			{
				value: 2,
				path: '/pagesA/aboutUs/aboutUs',
				jumpName: 'reLaunch'
			},
			//收藏
			{
				value: 2,
				path: '/pagesA/aboutUs/aboutUs',
				jumpName: 'reLaunch'
			},
			//日志
			{
				value: 3,
				path: '/pages/circle/detail',
				jumpName: 'reLaunch'
			},
			//榜单
			{
				value: 4,
				path: '/pagesA/popularityChart/popularityChart',
				jumpName: 'reLaunch'
			},
			//商城
			{
				value: 5,
				path: '/pagesA/shopping/detail',
				jumpName: 'reLaunch'
			},
			//视频
			{
				value: 6,
				path: '/pagesB/teachingCourses/teachingCourses',
				jumpName: 'reLaunch'
			},
		],
		is_request: false, //是否收藏进入
    },
	getters: {
	    getIsRequest: state => {
	        return state.is_request;
	    }
	},
    mutations: {
		setCjj(state, cjj) {
			state.cjj = cjj
		},
		setVideoMask(state, videoMask) {
			state.videoMask = videoMask
		},
		setIsRequest(state, is_request) {
			state.is_request = is_request
		},
		setPublishUrl(state, publishUrl) {
			state.publishUrl = publishUrl
		},
		setCardInfo(state, cardInfo) {
			state.cardInfo = cardInfo
		},
		setIsCircleRefresh(state, isCircleRefresh) {
			state.isCircleRefresh = isCircleRefresh
		},
		setIsRefresh(state, isRefresh) {
		    state.isRefresh = isRefresh
		},
		setMessageCount(state, messageCount) {
		    state.messageCount = messageCount
		},
        setOssurl(state, userInfo) {
            state.userInfo = userInfo
        },
		setAddress(state,address){
			state.latitude = address.latitude
			state.longitude = address.longitude
		},
		setCity(state,city){
			state.city = city
		},
		setCropperUrl(state,cropperUrl){
			state.cropperUrl = cropperUrl
		},
		setShareCropperUrl(state,shareCropperUrl){
			state.shareCropperUrl = shareCropperUrl
		},
		setShareQuery(state,shareQuery){
			state.shareQuery = shareQuery
		},
		setShare(state,share){
			state.share = share
		},
		setUserInfo(state,userInfo){
			state.userInfo = userInfo
		},
		setSystemInfo(state,systemInfo){
			state.systemInfo = systemInfo
		},
    },
    actions: {
		//跳转处理参数
		handel({ state, commit }, e) {
			console.log('handel', e)
			state.config.forEach(i=>{
				if(i.value === Number(e.is_mixin_collect)) {
					let query = ''
					if(e) {
						query = '?'
						for(let j in e) {
							if(j != 'is_mixin_collect') {
								query += `${j}=${e[j]}&`
							}
						}
						const lastChar = query[query.length - 1];
						if(lastChar === '&') {
							query = query.substring(0, query.length - 1)
						}
					}
					console.log('i.path', i, query)
					commit('setIsRequest', false)
					uni[i.jumpName]({
						url: i.path + query,
					})
				}
			})
		},
		login({commit}, params) {
			return new Promise((res,rej)=>{
				console.log('login')
				uni.login({
					provider: 'weixin',
					success: loginRes => {
						
						console.log('loginRes', loginRes)
						let data = {
							code: loginRes.code
						}
						if (params.userId) {
							data['share_userId'] = params.userId
						}
						if (params.shareId) {
							data['login_share_business_card_id'] = params.shareId
						}
						console.log('data', data, params)
						InformationUserCodeLogin(data).then(d =>{
							uni.setStorageSync("token", d.data.token)
							res()
						}).catch(err=> {
							rej(err)
						})
					},
					fail(err) {
						console.log('err', err)
						rej(err)
					}
				});
			})
		},
		getScreenWidth({ commit }) {
			uni.getSystemInfo({
				success: function(res) {
					console.log("屏幕宽度: ", res);
					commit('setSystemInfo', res)
				},
				fail: function(err) {
					console.error("获取屏幕宽度失败: ", err);
				}
			});
		},
		async updateMessageCount({ commit }) {
			let token = uni.getStorageSync('token')
			if(!token) return
			const res = await InformationMassageCount()
			if(res.data > 0) {
				uni.setTabBarBadge({
					index: 1,
					text:res.data > 99 ? '99+' : res.data.toString()
				})
			} else {
				uni.removeTabBarBadge({
					index: 1
				})
			}
			commit('setMessageCount',res.data || 0)
		},
        updateUserInfo({ commit }, userInfo) {
            commit('setAddress', userInfo)
        },
		getAddress({ commit,dispatch }, type = 1){
			// 获取当前位置
			uni.getLocation({
			  type: 'wgs84',
			  success: async function(res) {
			    const latitude = res.latitude;
			    const longitude = res.longitude;
				commit('setAddress', {
					latitude,
					longitude
				})
			    console.log('纬度:', latitude, '经度:', longitude);
			    // 调用反向地理编码API获取城市信息
				const r = await dispatch('getCityFromLocation',{
					latitude,
					longitude
				})
				if(type === 2) {
					InformationPositioningCity({PositioningCity: r}).then(res=>{
						
					})
				}
			  },
			  fail: function(err) {
			    console.error('获取位置失败', err);
			  }
			});
		},
		getCityFromLocation({ commit,state },res){
			return new Promise((resove,reject)=>{
				console.log('res', res)
				//let url = `https://apis.map.qq.com/ws/geocoder/v1/?location=${res.latitude},${res.longitude}&key=${state.mapKey}`
				let url = `https://api.tianditu.gov.cn/geocoder?postStr={'lon':${res.longitude},'lat':${res.latitude},'ver':1}&type=geocode&tk=4feea91b0e2b0cc4dbaa08560a64f12a`
				uni.request({
				   url,
				   success: function(res) {
									console.log('res', res);
				     if (res.data.result) {
				       const city = res.data.result.addressComponent.province;
				       console.log('当前城市:', city);
									commit('setCity', city)
				       // 可以在这里进行其他操作，比如将城市信息保存到 Vuex 中
					   resove(city)
				     }
				   },
				   fail: function() {
				     console.error('获取城市信息失败');
					 reject()
				   }
				 });
			})
			 
		},
		async getShare({ commit,dispatch },params = {}){
			let data = {}
			if(params.business_card_id) {
				data['business_card_id'] = params.business_card_id
			}
			if(params.user_id) {
				data['user_id'] = params.user_id
			}
			console.log('分享接口',data)
			const res = await InformationSharePictures(data)
			commit('setShare', res.data)
			let token = uni.getStorageSync('token')
			if(token) {
				dispatch('getUserInfo')
			}
			
			return res
		},
		async getUserInfo({ commit }, business_card_id = ''){
			const res = await InformationUserInfo()
			commit('setUserInfo', res.data)
			return res
		},
		getCity({ commit,dispatch }){
			return new Promise((resolve, reject) => {
				// 获取当前位置
				uni.getLocation({
				  type: 'wgs84',
				  success: function(res) {
				    const latitude = res.latitude;
				    const longitude = res.longitude;
					commit('setAddress', {
						latitude,
						longitude
					})
				    console.log('纬度:', latitude, '经度:', longitude);
				    // 调用反向地理编码API获取城市信息
					dispatch('getCityFromLocation',{
						latitude,
						longitude
					}).then(r=>{
						resolve(r)
					})
					
				  },
				  fail: function(err) {
				    console.error('获取位置失败', err);
					reject('获取位置失败')
				  }
				});
			})
		}
    }
})

export default store